package com.example.demo.service.impl;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Verify;
import com.example.demo.enums.ApiErrorEnum;
import com.example.demo.expcetion.ApiException;
import com.example.demo.mapper.VerifyMapper;
import com.example.demo.service.SMSService;
import com.example.demo.service.VerifyService;
import com.example.demo.util.RandomUtil;
import com.example.demo.vo.request.UpdatePasswordRequest;

@Service
public class VerifyServiceImpl extends ServiceImpl<VerifyMapper, Verify> implements VerifyService {

	private static final Logger LOGGER = LoggerFactory.getLogger(VerifyServiceImpl.class);
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private SMSService smsService;
	@Autowired
	private VerifyService verifyService;
	// 用户的缓存前缀
	private final String USER_CACHE_KEY = "USER";
	private final String USER_CACHE_LIST_KEY = "USER_LIST";
	int appid = 1400221888; // SDK AppID 以1400开头

	// 短信应用 SDK AppKey
	String appkey = "59760ee089cdec05a2d0d2eb9456d733";

//	    @Override
//	    public boolean getByPhone(String phone) {
//	        boolean isExist = super.removeById(phone);
//	        if (isExist) {
//	            // 清除缓存
//	            LOGGER.debug("清除缓存{}",phone);
//
//	            redisTemplate.delete(USER_CACHE_KEY+String.valueOf(phone));
//	        }
//	        return isExist;
//	    }
	@Override
	public void sendMsg(String phone) {
		// 判断手机号是否存在
		long count;
		Verify user = getUserByPhone(phone);
		if (user == null) {
			throw new ApiException(ApiErrorEnum.ERROR_1003);
		}
	//count =redisTemplate.opsForValue().increment(phone.concat(TimeUnit.MINUTES),1);
		count =redisTemplate.opsForValue().increment(phone.concat(phone),1);
		if(count>10) {
			 throw new ApiException(ApiErrorEnum.ERROR_1003);
		}else {
			 Duration duration=Duration.between(LocalDateTime.now(), LocalDate.now().plusDays(1));
			 redisTemplate.expire(phone.concat(phone), duration.toDays(), TimeUnit.MINUTES);
		}
		// 拼接短信内容,你的验证码是。。
		String code = RandomUtil.getRandNum(6);
		smsService.sendCodeMsg(phone, code);
		// 存储到redis，redisTemplate写到redis,key=verifyCode:18577772222:002222,
		// 存储到redis，redisTemplate写到redis,key=verifyCode:18577772222  value=002222,
		redisTemplate.opsForValue().set("verifyCode:"+phone+":"+code, "", 10, TimeUnit.MINUTES);
	}

	@Override
	public void updatePassword(UpdatePasswordRequest record) {
		// 验证密码是否为空
		if (record == null) {
			throw new ApiException(ApiErrorEnum.ERROR_100);
		}
		String key = "verifyCode:"+record.getPhone()+":"+record.getVerifyCode();
		//存在验证码
		if(!redisTemplate.hasKey(key)) {
			throw new ApiException(ApiErrorEnum.ERROR_1004);
		}
		//修改密码
		updatePw(record);
		//删除缓存
		redisTemplate.delete(key);
		// 清理掉redis key
		LOGGER.debug("清除缓存{}", key);
	}

	private void updatePw(UpdatePasswordRequest record) {
		Verify user = getUserByPhone(record.getPhone());
		user.setPassWord(record.getPassword());
		super.updateById(user);
	}

	@Override
	public Verify getUserByPhone(String phone) {
		QueryWrapper<Verify> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Verify::getUserPhone, phone);
		return super.getOne(queryWrapper);
	}
}
